package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Employee;
import com.kaishengit.entity.Message;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.RowMapper;

public class MessageDao {
	DBHelp<Message> db = new DBHelp<Message>();

	public void add(Message m) {
		final String sql = "INSERT INTO t_message(id,content,createtime,projectid,employeeid) VALUES(?,?,?,?,?)";
		db.executeSQL(sql, m.getId(),m.getContent(),m.getCreatetime(),m.getProjectid(),m.getEmployeeid());
	}

	public List<Message> findById(String projectid) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT tm.id ,content,createtime,projectid,employeeid , te.username, email,pic ");
		sql.append("FROM t_message AS tm LEFT JOIN t_employee AS te ON employeeid = te.id where projectid = ?");
		return db.executeQueryForList(sql.toString(), new MessageRowMapper(), projectid);
	}
	
	private class MessageRowMapper implements RowMapper<Message> {

		public Message mapRow(ResultSet rs) throws SQLException {
			Message m = new Message();
			m.setContent(rs.getString("content"));
			m.setCreatetime(rs.getString("createtime"));
			m.setEmployeeid(rs.getString("employeeid"));
			m.setId(rs.getString("id"));
			m.setProjectid(rs.getString("projectid"));
			
			Employee e = new Employee();
			e.setEmail(rs.getString("email"));
			e.setId(rs.getString("employeeid"));
			e.setPic(rs.getString("pic"));
			e.setUsername(rs.getString("username"));
			
			m.setEmployee(e);
			
			
			return m;
		}
		
	}
	
}
